﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace WindowsPhone_Map_TTTN
{
    class MapSocketUDP
    {
        public MapSocketUDP()
        {
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
           
        }

        public static MapSocketUDP getInstance()
        {
            if (_instance==null) _instance = new MapSocketUDP();
            return _instance;
        }


        public String send(string data)
        {
            string response = "Operation Timeout";
            if (_socket != null)
            {
                SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
                socketEventArg.RemoteEndPoint = new DnsEndPoint(MConfig.gps_host, MConfig.gps_port);
                // Inline event handler for the Completed event.
                // Note: This event handler was implemented inline in order to make this method self-contained.
                socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
                {
                    response = e.SocketError.ToString();
                    // Unblock the UI thread
                    _clientDone.Set();
                });
                // Add the data to be sent into the buffer
                byte[] payload = Encoding.UTF8.GetBytes(data);
                socketEventArg.SetBuffer(payload, 0, payload.Length);
                // Sets the state of the event to nonsignaled, causing threads to block
                _clientDone.Reset();
                // Make an asynchronous Send request over the socket
                _socket.SendToAsync(socketEventArg);
                // Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds.
                // If no response comes back within this time then proceed
                _clientDone.WaitOne(TIMEOUT_MILLISECONDS);
            }
            else
            {
                response = "Socket is not initialized";
            }
            return response;
        }
        public int recieve()
        {
            return 0;
        }
        //private static SocketAsyncEventArgs socketEventArg;
        private static Socket _socket;
        private const int TIMEOUT_MILLISECONDS = 5000;
        private const int MAX_BUFFER_SIZE = 2048;
        private static ManualResetEvent _clientDone = new ManualResetEvent(false);
        public static MapSocketUDP _instance;
    }
}
